import { ipcRenderer } from 'electron';
import _ from 'lodash';
import transition from '@/transition';

const state = {
    selectedDirectory: null,
    activePicture: {},
    enterClass: '',
    leaveClass: '',
    showImage: false,
    loading: false,
    contentWidth: 0,
    contentHeight: 0
};

const getters = {
    isDirectorySelected(state) {
        return !_.isNull(state.selectedDirectory);
    }
};

const mutations = {
    selectDirectory(state, payload) {
        state.selectedDirectory = payload.directory;
    },
    selectImage(state, payload) {
        state.activePicture = _.clone(payload.image);
    },
    hideImage(state) {
        state.showImage = false;
    },
    showImage(state) {
        state.showImage = true;
    },
    setTransition(state, payload) {
        state.enterClass = `animated ${payload.in}`;
        state.leaveClass = `animated ${payload.out}`;
    },
    setContentSize(state, payload) {
        state.contentWidth = payload.width;
        state.contentHeight = payload.height;
    },
    setLoading(state) {
        state.loading = true;
    },
    cancelLoading(state) {
        state.loading = false;
    }
};

let lagTimer = null;

const actions = {
    pendingDirectorySelect({ commit }) {
        ipcRenderer.send('select-directory');
    },
    pendingImageSelect({ commit, dispatch }) {
        dispatch('play');
        ipcRenderer.send('select-image');
        clearTimeout(lagTimer);
        lagTimer = setTimeout(() => commit('setLoading'), 500);
    },
    selectDirectory({ commit, dispatch }, payload) {
        commit('selectDirectory', { directory: payload });
        dispatch('pendingImageSelect');
        dispatch('hideMenu');
    },
    selectImage({ commit, dispatch }, payload) {
        if (_.isNull(payload)) {
            _.delay(() => dispatch('pendingImageSelect'), 500);
            commit('setLoading');
            return;
        }
        if (_.isEmpty(payload)) {
            commit('selectImage', { image: {} });
            dispatch('pause');
            return;
        }
        clearTimeout(lagTimer);
        commit('selectImage', { image: payload });
        dispatch('selectTransition');
        commit('cancelLoading');
        _.delay(() => dispatch('showImage'), 500);
    },
    hideImage({ commit }) {
        commit('hideImage');
    },
    showImage({ commit }) {
        commit('showImage');
    },
    selectTransition({ commit }) {
        commit('setTransition', {
            in: transition.in[_.random(transition.in.length - 1)],
            out: transition.out[_.random(transition.out.length - 1)]
        });
    },
    setContentSize({ commit }, payload) {
        commit('setContentSize', { width: payload[0], height: payload[1] });
    }
};

export default {
    state,
    getters,
    mutations,
    actions
};
